﻿@using TestOnlineProject.Models.Entities
@{
    ViewBag.Title = "Import";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<script>
    $(document).ready(function () {
        $('input[type=file]').bootstrapFileInput();
    });
</script>
@{
    if (ViewBag.Msg != null)
    {
    <script>        alert("@ViewBag.Msg")</script>
    }
}
<div class="site_map">
    @Html.ActionLink("Home", "Index", "Home")
    / @Html.ActionLink("Subjects", "Index", "Subject")
    / @Html.ActionLink((string)ViewBag.Subject.Code, "Details", "Subject", new { id = ViewBag.Subject.SubjectId }, null)
    /
    @if (@ViewBag.Section != null)
    {
        @Html.ActionLink("Sections", "Index", "Section", new { subjectId = @ViewBag.Subject.SubjectId }, null)
        <span>/</span>
        <span style="word-wrap: break-word">
            @Html.ActionLink((string)@ViewBag.Section.Name, "Index", "Question", new { subjectId = @ViewBag.Subject.SubjectId, sectionId = @ViewBag.Section.SectionId }, null)
        </span>
    }
    else
    {
        @Html.ActionLink("Questions", "Index", "Question", new { subjectId = @ViewBag.Subject.SubjectId }, null)  
    }
    / Import Question
</div>
<br />
<div class="main_nav">
    <span><a href="@Url.Content("~/Question/Index")?subjectId=@ViewBag.Subject.SubjectId">
        <img src="@Url.Content("~/Images/back button.png")" alt="Back"/>
    </a></span>
</div>
<br />
<fieldset>
    <form onsubmit="return false;" id="QuestionImport">
    <table class="table table-bordered">
        <tr>
            <td style="width: 100px; text-align: right">
                Section
            </td>
            <td>
                @if (ViewBag.Section != null)
                {
                    @ViewBag.Section.Name
                    <input type="hidden" name="SectionId" value="@ViewBag.Section.SectionId" />
                }
                else
                {
                    <span>
                        @Html.DropDownList("SectionId", ViewBag.SectionMineList as SelectList, new { name = "Section" })
                    </span>
                }
            </td>
        </tr>
        <tr>
            <td style="width: 100px; text-align: right">
                Text File
            </td>
            <td>
                <input type="file" name="FileUpload" id="FileUpload" title="Browse" accept="text/*" />
                <img src="@Url.Content("~/Images/loading.gif")" id="loadImage" width="28px" alt=""/>
            </td>
        </tr>
        <tr>
            <td>
            </td>
            <td>
                Maximum size of file: 2MB
            </td>
        </tr>
        <tr>
            <td style="text-align: right">
            </td>
            <td>@Html.ActionLink("Download Template", "DownloadTemplate") | @Html.ActionLink("Download Guide", "DownloadGuide")
            </td>
        </tr>
        <tr>
            <td style="text-align: right">
            </td>
            <td>
                <button id="submitFile" class="btn" style="width: 90px">
                    Import</button>
                @if (@ViewBag.Section != null)
                {
                    @Html.ActionLink("Reset", "Import", new { id = ViewBag.Subject.SubjectId, sectionId = @ViewBag.Section.SectionId }, new { style = "width: 54px", @class = "btn" })
                    @Html.ActionLink("Cancel", "Index", new { subjectId = ViewBag.Subject.SubjectId, sectionId = @ViewBag.Section.SectionId }, new { style = "width: 54px", @class = "btn" })
                }
                else
                {
                    @Html.ActionLink("Reset", "Import", null, new { style = "width: 54px", @class = "btn" })
                    @Html.ActionLink("Cancel", "Index", new { subjectId = ViewBag.Subject.SubjectId }, new { style = "width: 54px", @class = "btn" })
                }
            </td>
        </tr>
    </table>
    </form>
</fieldset>
<script>
    var subjectId = @Session["subjectId"];
    $(document).ready(function() {
        $('#submitFile').click(function(e) {
            alert('Please select the file.');
        });

        $("#loadImage").hide();
        var sectionId = $("input[name=SectionId]").val();
        $('#FileUpload').fileupload({
            url: '@Url.Content("~/Question/Import")',
            dataType: 'json',
            autoUpload: true,
            limitMultiFileUploads: 1,
            singleFileUploads: true,
            add: function(e, data) {
                var uploadErrors = [];
                var acceptFileTypes = /(\.|\/)(txt)$/i;
                if (data.originalFiles[0]['type'].length && !acceptFileTypes.test(data.originalFiles[0]['name'])) {
                    alert('Not an accepted file type');
                    if (sectionId != "") {
                        window.location = "@Url.Content("~/Question/Import")?id=@ViewBag.Subject.SubjectId&sectionId=" + sectionId;
                    } else {
                        window.location = "@Url.Content("~/Question/Import")?id=@ViewBag.Subject.SubjectId";
                    }
                }

                if (data.originalFiles[0].size > 2000000) {
                    alert('Your file is out of size!');
                    if (sectionId != "") {
                        window.location = "@Url.Content("~/Question/Import")?id=@ViewBag.Subject.SubjectId&sectionId=" + sectionId;
                    } else {
                        window.location = "@Url.Content("~/Question/Import")?id=@ViewBag.Subject.SubjectId";
                    }
                }
                
                if (uploadErrors.length > 0) {
                    alert(uploadErrors.join("\n"));
                } else {
                    data.context = $('#submitFile');
                    $("#submitFile").unbind('click');
                    $('#submitFile').click(function(e) {
                        $("#loadImage").show();
                        e.stopPropagation();
                        data.submit();
                        document.getElementById("FileUpload").disabled = true;

                    });
                }
            },
            done: function(e, data) {
                if (data.result.success) {
                    alert("Import success " + data.result.successQuestion + " questions, Dublicate " + data.result.dublicateQuestion + " questions!");
                    if(data.result.successQuestion != 0){
                        if (sectionId != "") {
                            window.location = '@Url.Content("~/Question/ImportResult")?sectionId=' + sectionId;
                        } else {
                            window.location = '@Url.Content("~/Question/ImportResult")';
                        }
                    } 
                    else
                    {
                        if (sectionId != "") 
                        {
                            window.location = "@Url.Content("~/Question/Import")?id=@ViewBag.Subject.SubjectId&sectionId=" + sectionId;
                        } 
                        else 
                            {
                            window.location = "@Url.Content("~/Question/Import")?id=@ViewBag.Subject.SubjectId";
                            }
                    }
                } else {
                    alert(data.result.error);
                    if (sectionId != "") {
                        window.location = "@Url.Content("~/Question/Import")?id=@ViewBag.Subject.SubjectId&sectionId=" + sectionId;
                    } else {
                        window.location = "@Url.Content("~/Question/Import")?id=@ViewBag.Subject.SubjectId";
                    }
                }
            },
            fail: function(e, data) {
                $('#submitFileStatus').text('');
                if (typeof(error) == 'undefined') {
                    console.log("Upload error");
                    console.log(e);
                    console.log(data);
                } else {
                    error(e, data);
                }
            }
        });
    });
</script>
